<template>
  <div class="comDetail">
    <div class="main-header">
      <el-steps :active="active" align-center finish-status="success">
        <el-step title="商品基本信息" />
        <el-step title="添加库存信息" />
        <el-step title="添加移动端信息" />
      </el-steps>
    </div>
    <el-card shadow="nerve">
      <div class="main-body">
        <el-form
          ref="productInfo"
          :model="productInfo"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <div v-if="active === 0" class="step1">
            <!-- 基本信息 -->
            <div>
              <div class="form-title">基本信息</div>
              <div class="form-main">
                <el-form-item label="商品名称" prop="name">
                  <el-input v-model="productInfo.name" size="mini" />
                </el-form-item>
                <el-form-item label="商品编码" prop="productSn">
                  <el-input v-model="productInfo.productSn" size="mini" />
                </el-form-item>
                <el-form-item label="商品分类" prop="productCategoryName">
                  <el-select
                    v-model="productInfo.productCategoryName"
                    size="mini"
                    placeholder="请选择商品分类"
                  >
                    <el-option label="创意" value="创意" />
                    <el-option label="风格" value="风格" />
                    <el-option label="饰品" value="饰品" />
                    <el-option label="灯具" value="灯具" />
                  </el-select>
                </el-form-item>
                <el-form-item label="商品品牌" prop="brandName">
                  <el-select
                    v-model="productInfo.brandId"
                    size="mini"
                    placeholder="品牌"
                    clearable
                  >
                    <el-option
                      v-for="item in brandList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item class="desc" label="商品描述" prop="detailDesc">
                  <el-input v-model="productInfo.description" type="textarea" />
                </el-form-item>
              </div>
            </div>
            <!-- 商品信息 -->
            <div>
              <div class="form-title">商品信息</div>
              <div class="form-main">
                <el-form-item label="商品原价" prop="price">
                  <el-input-number
                    v-model="productInfo.originalPrice"
                    size="mini"
                  />
                </el-form-item>
                <el-form-item label="促销价格">
                  <el-input v-model="productInfo.promotionPrice" size="mini" />
                </el-form-item>
                <el-form-item label="促销类型">
                  <el-input v-model="productInfo.promotionType" size="mini" />
                </el-form-item>
                <el-form-item label="重量">
                  <el-input-number v-model="productInfo.weight" size="mini" />
                </el-form-item>
                <el-form-item label="审核状态:" size="normal">
                  <el-switch
                    v-model="productInfo.verifyStatus"
                    size="mini"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
                <el-form-item label="是否上架:" size="normal">
                  <el-switch
                    v-model="productInfo.publishStatus"
                    size="mini"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
                <el-form-item label="缩略图:" size="normal">
                  <el-upload
                    :headers="headers"
                    :action="baseUrl"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-success="handleSuccess"
                  >
                    <i class="el-icon-plus" />
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="productInfo.pic" />
                  </el-dialog>
                </el-form-item>
              </div>
            </div>
            <!-- //其他信息 -->
            <div>
              <div class="form-title">其他信息</div>
              <div class="form-main">
                <el-form-item label="推荐状态:" size="normal">
                  <el-switch
                    v-model="productInfo.recommendStatus"
                    size="mini"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
                <el-form-item label="新品状态:" size="normal">
                  <el-switch
                    v-model="productInfo.newStatus"
                    size="mini"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
                <el-form-item label="预告商品:" size="normal">
                  <el-switch
                    v-model="productInfo.previewStatus"
                    size="mini"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
                <el-form-item label="搜索关键词">
                  <el-input v-model="productInfo.keywords" size="mini" />
                </el-form-item>

                <el-form-item label="库存预警" prop="lowStock">
                  <el-input-number v-model="productInfo.lowStock" size="mini" />
                </el-form-item>
                <el-form-item label="商品排序">
                  <el-input v-model="productInfo.sort" size="mini" />
                </el-form-item>
                <el-form-item class="serve" label="产品服务">
                  <el-checkbox-group v-model="serviceIds">
                    <el-checkbox label="无忧退货" name="serviceIds" />
                    <el-checkbox label="快速退款" name="serviceIds" />
                    <el-checkbox name="serviceIds" label="免费包邮"
                  /></el-checkbox-group>
                </el-form-item>
              </div>
            </div>
          </div>
          <div v-if="active === 1" class="step2">
            <div>
              <div class="form-title">商品sku信息</div>
              <div class="form-main">
                <el-form-item label="标题">
                  <el-input v-model="productInfo.detailTitle" size="mini" />
                </el-form-item>
                <el-form-item label="副标题">
                  <el-input v-model="productInfo.subTitle" size="mini" />
                </el-form-item>
                <el-form-item class="uploadPic" label="画册图片:" size="normal">
                  <el-upload
                    :headers="headers"
                    :action="baseUrl"
                    :file-list="album"
                    :on-preview="handlePictureCardPreview"
                    :before-upload="rechecSize"
                    list-type="picture-card"
                    :on-success="handleAlbum"
                  >
                    <i class="el-icon-plus" />
                    <div slot="tip" class="el-upload__tip">
                      只能上传jpg/png文件，单个文件不超过500kb,不能超过5个
                    </div>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" />
                  </el-dialog>
                </el-form-item>
                <el-form-item
                  label="sku设置:"
                  class="createdItem"
                  size="normal"
                >
                  <el-input
                    v-model="skuObj.color.text"
                    placeholder="颜色描述:比如土豪金"
                    size="mini"
                    clearable
                  />
                  <el-button type="default" @click="createColor"
                    >创建颜色选项</el-button
                  >
                  <el-input
                    v-model="skuObj.size.text"
                    placeholder="商品大小"
                    size="mini"
                    clearable
                  />
                  <el-button type="default" @click="createSize"
                    >创建大小选项</el-button
                  >
                </el-form-item>
                <el-form-item class="createBtn" size="normal">
                  <el-button
                    type="primary"
                    size="default"
                    @click="createSkuList"
                    >生成sku列表</el-button
                  >
                  <el-button type="primary" size="default">新建sku</el-button>
                </el-form-item>
                <!-- 颜色 -->
                <el-form-item size="normal">
                  <el-checkbox-group
                    v-model="skuObj.color.selectedList"
                    size="small"
                  >
                    <el-checkbox
                      v-for="(item, index) in skuObj.color.list"
                      :key="index"
                      :label="item"
                    >
                      <span>{{ item }}</span>
                      <el-button
                        type="text"
                        size="small"
                        style="color: #f00; padding-left: 8px"
                        @click="
                          delItem(
                            index,
                            skuObj.color.list,
                            skuObj.color.selectedList
                          )
                        "
                        >删除</el-button
                      >
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <!-- 大小 -->
                <el-form-item size="normal">
                  <el-checkbox-group
                    v-model="skuObj.size.selectedList"
                    size="small"
                  >
                    <el-checkbox
                      v-for="(item, index) in skuObj.size.list"
                      :key="index"
                      ><span>{{ item }}</span>
                      <el-button
                        type="text"
                        style="color: #f00; padding-left: 5px"
                        size="mini"
                        @click="delItem(index, 'skuObj.size.list')"
                        >删除</el-button
                      >
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>

                <!-- 生成sku的列表 -->
                <el-table
                  v-show="skuList.length > 0"
                  size="mini"
                  :data="skuList"
                  border
                  stripe
                >
                  <el-table-column type="index" label="#" fixed="left" />

                  <el-table-column label="图片" :width="120">
                    <template slot-scope="scope">
                      <el-upload
                        style="width: 100px; height: 100px"
                        :action="baseUrl"
                        :headers="headers"
                        :show-file-list="false"
                        :on-success="handleTableSuccess"
                      >
                        <img
                          v-if="scope.row.pic"
                          style="width: 100px; height: 100px"
                          :src="scope.row.pic"
                          class="avatar"
                        />
                        <i
                          v-else
                          style="width: 100px; height: 100px; margin-top: -31px"
                          class="el-icon-plus avatar-uploader-icon"
                        />
                      </el-upload>
                    </template>
                  </el-table-column>
                  <el-table-column label="颜色" :width="160">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.spData[0].value"
                        size="mini"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="大小" :width="160">
                    <template slot-scope="scope">
                      <!-- 这里必须加 v-if，因为有些没有大小， 不加v-if会报错 -->
                      <el-input
                        v-if="scope.row.spData[1]"
                        v-model="scope.row.spData[1].value"
                        size="mini"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="库存" :width="200">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.stock"
                        size="mini"
                        placeholder="自定义库存"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="预警库存" :width="200">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.lowStock"
                        size="mini"
                        placeholder="预警库存"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="锁定库存" :width="200">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.lockStock"
                        size="mini"
                        placeholder="锁定库存"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="sku编码" :width="200">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.skuCode"
                        size="mini"
                        placeholder="自定义sku编码"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="价格" :width="160">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.price"
                        size="mini"
                        placeholder="价格,单位:分"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="销量" :width="160">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.sale" size="mini" />
                    </template>
                  </el-table-column>

                  <el-table-column fixed="right" label="操作" :width="160">
                    <template slot-scope="scope">
                      <el-button
                        style="color: red"
                        size="mini"
                        type="text"
                        @click="removeSku(scope.row)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
          <div v-if="active === 2" class="step3">
            <el-form-item label="描述信息" size="normal">
              <TinEditor ref="tin" />
            </el-form-item>
            <el-form-item label="备注信息" size="normal">
              <el-input
                v-model="productInfo.note"
                type="textarea"
                placeholder="请填写备注信息"
                size="mini"
                clearable
              />
            </el-form-item>
          </div>
        </el-form>
        <div class="main-footer">
          <el-button v-if="active === 0" type="primary" @click="active++"
            >下一步,填写库存信息</el-button
          >
          <el-button v-else-if="active !== 0" type="info" @click="active--"
            >返回上一步</el-button
          >
          <el-button v-if="active === 1" type="primary" @click="active++"
            >下一步,移动端信息</el-button
          >
          <el-button v-if="active === 2" type="primary" @click="submit"
            >提交保存</el-button
          >
        </div>
      </div></el-card
    >
  </div>
</template>
<script>
import TinEditor from '@/components/Tinymce'
import {
  addProductAndSkus,
  updateProductAndSkus
} from '@/api/commodities/commoditiesList/index'
import { findAllBrand } from '@/api/commodities/brandList/index'
import { uuid } from 'uuid'
import mixins from '@/mixins/index'
export default {
  components: {
    TinEditor
  },
  mixins: [mixins],
  data() {
    return {
      id: '', // 页面传递id,判断新增和修改
      skuList: [], // 生成的sku列表
      active: 1, // 步骤条
      productInfo: {}, // 产品信息
      brandList: [], // 品牌列表
      dialogImageUrl: '', // 缩略图地址
      album: [], // 画册
      dialogVisible: false, // 缩略图显示
      serviceIds: [], // 服务选项
      skuObj: {
        color: {
          text: '',
          list: [],
          selectedList: []
        },
        size: {
          text: '',
          list: [],
          selectedList: []
        }
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        price: [{ required: true, message: '请填写商品原价', trigger: 'blur' }],
        lowStock: [
          { required: true, message: '请填写库存最低数量', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.id = this.$route.params.id
    this.init()
  },
  mounted() {},
  methods: {
    init() {
      // 查询所有品牌分类
      findAllBrand().then((res) => {
        this.brandList = res.data.items
      })
    },
    // 查看图片缩略图
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 图片上传前检查
    rechecSize(file) {
      // 正则表达式
      if (!/jpeg|png|jpg/.test(file.type)) {
        this.$message.error('上传图片格式错误,请重新挑选!')
        return false
      }
      if (file.size > 1024 * 500) {
        this.$message.error('上传图片过大,请重新挑选!')
        return false
      }
    },
    // 处理图片上传
    handleSuccess(res) {
      if (res.success) {
        this.productInfo.pic = res.data.fileUrl
        this.$message.success('图片上传成功!')
      } else {
        this.$message.error('图片上传失败!')
      }
    },
    // 处理画册上传
    handleAlbum(res) {
      if (res.success) {
        this.album.push(res.data.fileUrl)
        this.$message.success('图片上传成功!')
      } else {
        this.$message.error('图片上传失败!')
      }
    },
    // 提交信息
    submit() {
      // 存在id 则修改 不存在新增
      // if (this.id) {
      //   updateProductAndSkus
      // } else {
      //   // 拼接字符串  产品服务
      //   this.productInfo.serviceIds = this.serviceIds.join(',')
      //   // 产品画册
      //   this.productInfo.album = this.album.join(',')
      //   // 获取富文本内容
      //   this.productInfo.detailMobileHtml = this.$refs.tin.getContent()
      //   // 体检新增商品信息
      //   addProductAndSkus({
      //     pmsSkuStockList: this.skuObj,
      //     product: this.productInfo
      //   }).then((res) => {
      //     console.log(res)
      //   })
      // }
    },
    // 创建sku 颜色选项
    createColor() {
      const color = this.skuObj.color
      color.list.push(color.text)
      color.text = ''
    },
    // 创建sku 大小选项
    createSize() {
      const size = this.skuObj.size
      size.list.push(size.text)
      size.text = ''
    },
    // 删除指定项
    delItem(index, str1, str2) {
      str1.splice(index, 1)
      str2.splice(index, 1)
    },
    // 生成sku列表
    createSkuList(type) {
      const sku = this.skuObj
      if (sku.color.selectedList.length < 1) {
        this.$message.error('请选中颜色')
        return
      }
      const publicObj = {
        pic: '',
        price: '',
        skuCode: '',
        stock: '',
        lowStock: ''
      }
      if (type !== 'add') {
        this.$confirm('此操作将清空sku列表,并生成新的列表, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.skuList = []
          this.$message({
            type: 'success',
            message: '创建成功!'
          })
        })
      }
      // 两层循环 首先生成必须要有颜色
      if (sku.size.selectedList.length > 0) {
        sku.color.selectedList.forEach((el) => {
          sku.size.selectedList.forEach((ele) => {
            const arr = [
              { key: '颜色', value: el },
              { key: '大小', value: ele }
            ]
            this.skuList.push({
              spDate: arr,
              tempId: uuid.v1(),
              ...publicObj
            })
          })
        })
      } else {
        sku.color.forEach((item) => {
          const arr = [{ key: '颜色', value: item }]
          this.skuList.push({
            spData: arr,
            tempId: uuid.v1(),
            ...publicObj
          })
        })
      }
      console.log(this.skuList)
    }
    // // 添加sku参数方法 第一个传对象,第二个传list
    // addSkuObj(skuobj, list) {
    //   const obj = Object.assign(
    //     {
    //       tempId: uuid.v1()
    //     },
    //     this[skuobj]
    //   )

    //   // 暂存列表 增加对象
    //   this[list].push(obj)
    //   // 情况暂存对象
    //   this[skuobj] = {}
    // }
  }
}
</script>

<style lang="scss" scoped>
.comDetail {
  .main-header {
    width: calc(100% + 60px);
    margin: -30px 0 30px -30px;
    padding: 30px 0;
    background-color: #fff;
  }
  .main-body {
    .form-title {
      font-size: 18px;
      font-weight: bold;
      padding-bottom: 20px;
      margin-bottom: 20px;
      border-bottom: 1px solid rgb(199, 199, 199);
    }
    .form-main {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      margin-bottom: 30px;
      .el-form-item {
        width: 30%;
        margin-right: 1%;
        margin: 10px;
        .el-input,
        .el-select {
          width: 100%;
        }
      }
      .desc,
      .serve,
      .uploadPic,
      .createBtn,
      .createdItem {
        width: 100%;
        .el-textarea {
          width: 60%;
        }
      }
    }
  }
  .main-footer {
    display: flex;
    justify-content: space-around;
    width: 500px;
    margin: 0 auto;
  }
}
</style>
